import configure.db_configure as db_configure
import configure.httpd_configure as httpd_configure
import listener.device_listener as device_listener
import wmi
import os
import logging
import common.codec_utils as codec_utils
from common.codec_utils import RSACipher
import common.date_utils as date_utils
import tkinter as tk
import tkinter.messagebox as messagebox


def get_disk_info():
    tmplist = []
    encrypt_str = ""
    c = wmi.WMI()
    for cpu in c.Win32_Processor():
        # cpu 序列号
        encrypt_str = encrypt_str + cpu.ProcessorId.strip()
        # print("cpu id:", cpu.ProcessorId.strip())
 
    for physical_disk in c.Win32_DiskDrive():
        encrypt_str = encrypt_str + physical_disk.SerialNumber.strip()
 
        # # 硬盘序列号
        # print('disk id:', physical_disk.SerialNumber.strip())
 
        # tmpdict = {}
        # tmpdict["Caption"] = physical_disk.Caption
        # tmpdict["Size"] = int(physical_disk.Size) / 1000 / 1000 / 1000
        # tmplist.append(tmpdict)
    for board_id in c.Win32_BaseBoard():
        # 主板序列号
        encrypt_str = encrypt_str + board_id.SerialNumber.strip()
        # print("main board id:", board_id.SerialNumber.strip())
 
    #          for mac in c.Win32_NetworkAdapter():
 
    # mac 地址（包括虚拟机的）
    #                    print "mac addr:", mac.MACAddress:
    for bios_id in c.Win32_BIOS():
        # bios 序列号
        bios = bios_id.qualifiers["UUID"].strip()[1:-1].replace("-","")
        encrypt_str = encrypt_str + bios
        # print("bios number:", bios)
        # print("encrypt_str:", encrypt_str)
 
    # 加密算法
   # print(zlib.adler32(encrypt_str))
    return codec_utils.base64encode(encrypt_str)


edit2=None
rsa = RSACipher(public_key_file=RSACipher.PUBLIC_KEY_PATH)
disk_info = get_disk_info()

def check():
    global edit2
    

    needLicense = False
    needLicenseText = None
    if not os.path.exists("license.txt"):
        needLicenseText = "license 不存在"
        needLicense = True
    else:
        try:
            with open("license.txt","r") as f:
                s123 = f.read().strip()
                sarr = s123.split(".")
                s12=".".join(sarr[0:2])
                s3 = sarr[2]

                verify_sign = rsa.verify_sign(s12,s3)
                if not verify_sign:
                    needLicenseText = "license 无效"
                    needLicense = True
                else:
                    s1 = sarr[0]
                    disk_info_equal = (s1 == disk_info)
                    if not disk_info_equal:
                        needLicenseText = "客户机信息 无效"
                        needLicense = True
                    else:
                        s2 = sarr[1]
                        expire = date_utils.parseDate(codec_utils.base64decode(s2))
                        timestampDet = expire.timestamp() - date_utils.now().timestamp() 
                        if timestampDet < 0:
                            needLicenseText = "license 已过期"
                            needLicense = True
        except Exception as e:
            needLicenseText = "license 异常"
            needLicense = True
    return needLicense,needLicenseText


def waitLicense(needLicenseText:str):
    global edit2

    # 创建主窗口
    root = tk.Tk()
    root.title("授权")
    # 设置窗口大小
    root.minsize(300,300)

    tk.Label(root,text="\n请复制机器标识给管理员，管理员将为您生成授权码\n").pack()

    lab = tk.Label(root,text="机器标识")
    lab.pack()
    edit = tk.Entry(root,textvariable = tk.StringVar(value=disk_info))
    edit.pack()


    lab2 = tk.Label(root,text="授权码")
    lab2.pack()
    edit2 = tk.Text(root, height=20, width=20)
    edit2.pack()

    lab3 = tk.Label(root,text=" ")
    lab3.pack()
    # 声明函数
    def okqqq():
        # 弹出对话框
        global edit2
        edit2_text = edit2.get(1.0, tk.END).strip()
        if edit2_text==None or edit2_text=="":
            messagebox.showerror(title = '错误',message="请填入授权码")# 返回值为True或者False
        else:
            with open("license.txt","w") as f:
                f.write(edit2_text)
            needLicense,needLicenseText = check()
            if needLicense:
                messagebox.showerror(title = '错误',message=needLicenseText)# 返回值为True或者False
            else:
                root.quit()
                root.destroy()
    # 添加按钮
    btn1 = tk.Button(root,text = '确定',command = okqqq)
    btn1.pack()

    def on_closing():
        os._exit(1)
    root.protocol("WM_DELETE_WINDOW", on_closing)
    # 加入消息循环
    root.mainloop()


def init():
    needLicense=True
    while needLicense:
        needLicense,needLicenseText = check()
        if needLicense:
            waitLicense(needLicenseText)

    db_configure.init()
    httpd_configure.init()
    device_listener.init()

def release():
    device_listener.release()